/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved.
 * distributed with this file and available online at
 */
package com.lap.auth.adapter.driving.persistence.role.repository;

import com.lap.auth.adapter.driving.persistence.role.RoleConverter;
import com.lap.auth.adapter.driving.persistence.role.mapper.RoleMapper;
import com.lap.auth.adapter.driving.persistence.role.po.RolePo;
import com.lap.auth.domain.role.Role;
import com.lap.auth.domain.role.repository.RoleRepository;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

@RequiredArgsConstructor
@Repository
public class RoleRepositoryImpl implements RoleRepository {

  private final RoleConverter roleConverter;
  private final RoleMapper roleMapper;

  @Override
  public Integer save(Role role) {
    RolePo rolePo = roleConverter.toPo(role);
    if (role.isNew()) {
      roleMapper.insert(rolePo);
      return rolePo.getId();
    }
    return roleMapper.updateByPrimaryKey(rolePo);
  }

  @Override
  public int deleteById(Integer id) {
    return roleMapper.deleteByPrimaryKey(id);
  }

  @Override
  public Optional<Role> findById(Integer id) {
    var rolePo = roleMapper.selectByPrimaryKey(id);
    return Optional.ofNullable(roleConverter.toDomain(rolePo));
  }

  @Override
  public boolean existsByCode(String code) {
    var rolePo = roleMapper.selectByCode(code);
    return rolePo != null;
  }

  @Override
  public List<Role> findByIds(Set<Integer> idSet) {
    if (idSet == null || idSet.isEmpty()) {
      return Collections.emptyList();
    }
    List<RolePo> list = roleMapper.selectByIds(idSet.stream().toList());
    return roleConverter.toDomains(list);
  }
}
